let autoUpdater = require("electron-updater").autoUpdater;
let electron = require('electron');
let app = electron.app;
let BrowserWindow = electron.BrowserWindow;
let mainWindow = null;
const Menu = electron.Menu;
const Tray = electron.Tray;
let appTray;


let updateUrl = "http://192.168.3.17:10996/version/"


const path = require('path')
const {nativeImage} = require("electron");
const ipc = electron.ipcMain

const ipcMain = electron.ipcMain

let ipcRenderer = require('electron').ipcRenderer

let appIcon = null

let isDebug = false;


ipc.on('put-in-tray', function (event) {
    const iconName = process.platform === 'win32' ? 'windows-icon.png' : 'iconTemplate.png'
    const iconPath = path.join(__dirname, iconName)

    appIcon = new Tray(iconPath)
    const contextMenu = Menu.buildFromTemplate([{
        label: '移除',
        click: function () {
            event.sender.send('tray-removed')
        }
    }])
    appIcon.setToolTip('在托盘中的 Electron 示例.')
    appIcon.setContextMenu(contextMenu)
})
ipc.on('remove-tray', function () {
    appIcon.destroy()
})
ipc.on('window-close', function () {
    mainWindow.close();
    appIcon.destroy();
    app.quit();
})
ipc.on("notification-click", function () {
    mainWindow.show();
})


app.on('window-all-closed', function () {
    if (appIcon) appIcon.destroy()
})

app.dock.hide();
app.on('ready', () => {

    // const iconName = process.platform === 'win32' ? 'windows-icon.png' : 'iconTemplate.png'
    const iconName = 'image/tray_icon.png';
    const iconPath = path.join(__dirname, iconName)
    let image = nativeImage.createFromPath(iconPath, 18);

    image.setTemplateImage(true);
    console.log(iconPath);
    appIcon = new Tray(image)
    appIcon.on('click', function (Event) {
        setTimeout(() => {
            let position = getPositionFromActiveDisplay(appIcon);
            mainWindow.setPosition(position.x, position.y, true);
            mainWindow.show();
        }, 100)
    })


    mainWindow = new BrowserWindow(
        {
            frame: false,
            // skipTaskbar:true,
            transparent: false,

            width: 300,
            height: 350,
            // height: 850,
            webPreferences: {nodeIntegration: true, contextIsolation: false}
        });
    mainWindow.loadFile('./html/login.html');
    // mainWindow.setSkipTaskbar(true);
    mainWindow.on('close', () => {
        mainWindow = null;
    })
    mainWindow.on('blur', () => {
        mainWindow.hide();
    })
    //检测更新
    //检测版本更新
    updateHandle(mainWindow, updateUrl);

    mainWindow.hide();
    if (!isDebug) {
        mainWindow.resizable = false
        mainWindow.setSkipTaskbar(true)
    } else {
        mainWindow.webContents.openDevTools()
    }

    // setTimeout(function(){
    //     autoUpdater.checkForUpdates();
    // },5000)


})


function updateHandle(window, feedUrl) {
    mainWindow = window;
    let message = {
        error: '检查更新出错',
        checking: '正在检查更新……',
        updateAva: '检测到新版本，正在下载……',
        updateNotAva: '现在使用的就是最新版本，不用更新',
    };
    //设置更新包的地址
    autoUpdater.setFeedURL(feedUrl);
    //监听升级失败事件
    autoUpdater.on('error', function (error) {
        console.log("更新失败");
        console.log(error);
        console.log("======================");
    });
    //监听开始检测更新事件
    autoUpdater.on('checking-for-update', function (message) {
        console.log("开始检查更新");
        console.log(message);
        console.log("======================");
    });
    //监听发现可用更新事件
    autoUpdater.on('update-available', function (message) {
        console.log("有可用更新");
        console.log(message);
        console.log("======================");
    });
    //监听没有可用更新事件
    autoUpdater.on('update-not-available', function (message) {
        console.log("没有可用的更新");
        console.log(message);
        console.log("======================");
    });

    // 更新下载进度事件
    autoUpdater.on('download-progress', function (progressObj) {
        console.log("更新下载进度");
        console.log(progressObj);
        console.log("======================");
    });
    //监听下载完成事件
    autoUpdater.on('update-downloaded', function (event, releaseNotes, releaseName, releaseDate, updateUrl) {


        console.log("下载完毕");
        console.log(releaseNotes);
        console.log(releaseName);
        console.log(releaseDate);
        console.log(updateUrl);
        console.log("======================");


        //退出并安装更新包
        autoUpdater.quitAndInstall();
    });


    //接收渲染进程消息，开始检查更新
    ipcMain.on("checkForUpdate", (e, arg) => {
        //执行自动更新检查
        // sendUpdateMessage({cmd:'checkForUpdate',message:arg})
        autoUpdater.checkForUpdates();
    })
}


const getPositionFromActiveDisplay = (tray) => {
    const trayBounds = tray.getBounds();
    const windowBounds = mainWindow.getBounds();
    const x = Math.round(trayBounds.x + trayBounds.width / 2 - windowBounds.width / 2);
    const y = Math.round(trayBounds.y + trayBounds.height);
    return {x, y};
};




